import axios from 'axios'

import envConfig from './config/env.config'
import router from '@/router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
class HttpRequest {

  constructor(config = {}) {
    this.instance = axios.create({
      baseURL: envConfig.baseURL, // 配置请求的根路径,可配合vite使用代理
      timeout: envConfig.timeout,
      // withCredentials: envConfig.withCredentials,
      ...config
    })
    this.pendingRequests = new Map() // 存储请求的集合（防重复请求）
    // 注册拦截器 
    this.instance.interceptors.request.use( // 请求拦截器
      (config) => {
        // 1. 防重复请求处理
        const requestId = this.getRequestIdentifier(config); // 生成请求标识
        if (this.pendingRequests.has(requestId)) {
          const pending = this.pendingRequests.get(requestId);
          pending.cancel('重复请求被取消');
        }
        config.cancelToken = new axios.CancelToken((cancel) => {
          this.pendingRequests.set(requestId, { cancel });
        });

        // 2. 通用请求头设置
        let token = localStorage.getItem('token');
        if (token && config.baseURL === envConfig.baseURL) { // 获取token
          token = JSON.parse(token).token;
          config.headers.Authorization = `Bearer ${token}`;
        }

        // 3. 开发环境日志
        if (envConfig.isDev) {
          console.log(`[${config.method.toUpperCase()}] ${config.url}`, config.data || config.params);
        }

        return config;
      },
      (error) => Promise.reject(error)
    )
    this.instance.interceptors.response.use( // 响应拦截器
      (response) => {
        // 1. 移除请求标识
        const requestId = this.getRequestIdentifier(response.config);
        this.pendingRequests.delete(requestId);

        // 2. 统一响应处理
        const res = response.data;
        if (res.code !== 200 && res.code !== 0) {
          // 业务错误处理
          const error = new Error(res.message || '请求失败');
          error.code = res.code;
          return Promise.reject(error);
        }

        return res.data||res.result; // 返回数据
      },
      (error) => { // 响应错误拦截器
        if (axios.isCancel(error)) {
          if (envConfig.isDev) console.log('请求已取消:', error.message);
          return Promise.reject(error);
        }
        // 响应错误处理
        const { response } = error;
        let errorMessage = '网络异常';
        let errorCode = -1;
        if (response) {
          errorCode = response.status;
          switch (response.status) {
            case 401:
              errorMessage = '未授权，请重新登录';
              const userStore = useUserStore();
              userStore.$reset()
              router.push('/login');
              // 这里可以添加跳转登录页逻辑
              break;
            case 403:
              errorMessage = '拒绝访问';
              break;
            case 404:
              errorMessage = '请求地址不存在';
              break;
            case 500:
              errorMessage = '服务器内部错误';
              break;
            default:
              errorMessage = response.data?.message || '请求失败';
          }
        } else if (error.request) {
          // 网络错误
          errorMessage = '网络连接失败，请检查您的网络';
        }
        console.log('error:', error);
        // 错误提示
        ElMessage.error(error.response.data?.message || errorMessage);

        return Promise.reject(new Error(errorMessage, { cause: errorCode }));
      }
    )

  }

  getRequestIdentifier = (config) => { // 生成请求标识
    const { method, url, params, data } = config;
    return [method, url, JSON.stringify(params), JSON.stringify(data)].join('&');
  };

  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }

  get(config) {
    return this.request({ ...config,  method: 'GET'})
  }
  post(config) {
    return this.request({ ...config, method: 'POST' })
  }
  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }
  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch(config) {
    return this.request({ ...config, method: 'PATCH' })
  }

}

export const BaseRequest = new HttpRequest() // 创建一个基础实例

export const YingTianRequest = new HttpRequest({
  baseURL: envConfig.yingtianURL
})

export const XYRequest = new HttpRequest({
  baseURL: envConfig.xygengURL
})

